package dao

import (
	"advertising/internal/dal"
	"advertising/internal/models"
	"context"
	"strings"

	"192.168.1.75/go-pkg/helper"
	"gorm.io/gorm"
)

type MerchantPublishDeviceGroup struct{}

func (MerchantPublishDeviceGroup) Create(ctx context.Context, db *gorm.DB, merchantID, groupID string) (err error) {
	m := dal.Use(db).MerchantPublishDeviceGroup
	var InsertData models.MerchantPublishDeviceGroup
	InsertData.ID, _ = helper.UUID{}.String()
	InsertData.MerchantID = merchantID
	InsertData.GroupID = groupID
	m.WithContext(ctx).Create(&InsertData)
	return nil
}

func (MerchantPublishDeviceGroup) List(ctx context.Context, db *gorm.DB, merchantID, groupID string, page, limit int) (res []*models.MerchantPublishDeviceGroup, count int64, err error) {
	m := dal.Use(db).MerchantPublishDeviceGroup
	tx := m.WithContext(ctx)
	if merchantID != "" {
		if strings.Contains(merchantID, ",") {
			tx = tx.Where(m.MerchantID.In(strings.Split(merchantID, ",")...))
		} else {
			tx = tx.Where(m.MerchantID.Eq(merchantID))
		}
	}
	if groupID != "" {
		tx = tx.Where(m.GroupID.Eq(groupID))
	}
	return tx.FindByPage(Offset(page, limit))
}

// 更新商户的投放分组
func (MerchantPublishDeviceGroup) UpdateGoupID(ctx context.Context, db *gorm.DB, merchantID, groupID string) (err error) {
	if merchantID == "" {
		return
	}
	m := dal.Use(db).MerchantPublishDeviceGroup
	m.WithContext(ctx).
		Where(m.MerchantID.Eq(merchantID)).
		UpdateColumn(m.GroupID, groupID)
	return nil
}

// 详情
func (MerchantPublishDeviceGroup) Detail(ctx context.Context, db *gorm.DB, merchantID, groupID string) (result *models.MerchantPublishDeviceGroup, count int64) {
	m := dal.Use(db).MerchantPublishDeviceGroup
	tx := m.WithContext(ctx)
	if merchantID != "" {
		tx = tx.Where(m.MerchantID.Eq(merchantID))
	}
	if groupID != "" {
		tx = tx.Where(m.GroupID.Eq(groupID))
	}
	count, _ = tx.Count()
	result, _ = tx.Take()
	return
}

// 商户已授权机器
func (MerchantPublishDeviceGroup) MerchantAuthorizedDevice(ctx context.Context, db *gorm.DB, merchantID string) (res []string, err error) {
	mg := dal.Use(db).MerchantPublishDeviceGroup
	dg := dal.Use(db).PublishDeviceGroup
	device := dal.Use(db).PublishDevice
	tx := mg.WithContext(ctx)

	tx.Join(dg, dg.ID.EqCol(mg.GroupID)).
		Join(device, device.GroupID.EqCol(dg.ID)).
		Where(mg.MerchantID.Eq(merchantID)).
		Where(dg.DeletedAt.Eq(0)).
		Pluck(device.RobotName, &res)
	return res, nil
}
